package com.lagou.edu.service.impl;

import com.lagou.edu.dao.entity.Token;
import com.lagou.edu.dao.repository.TokenRepository;
import com.lagou.edu.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.UUID;

/**
 * @author bobcheng
 * @date 2020/7/13
 */
@Service
@org.apache.dubbo.config.annotation.Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenRepository tokenRepository;

    @Override
    public void addToken(String email, HttpServletResponse response) {
        Optional<Token> optional = Optional.ofNullable(tokenRepository.findTopByEmail(email));
        Token entity = optional.orElse(Token.builder().email(email).build());
        String token = UUID.randomUUID().toString();
        entity.setToken(token);
        tokenRepository.save(entity);
        Cookie cookie = new Cookie("oauth_token", token);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setMaxAge(1800);
        response.addCookie(cookie);
    }

}
